﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LockScreen1
{
    public class MouseIdleMonitor
    {
        private Point lastPosition;
        private System.Windows.Forms.Timer timer;
        private int idleSeconds;

        /// <summary>
        /// 当鼠标空闲时触发
        /// </summary>
        public event Action OnMouseIdle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="checkIntervalMs">检查间隔（毫秒）</param>
        /// <param name="idleThresholdSeconds">鼠标闲置阈值（秒）</param>
        public MouseIdleMonitor(int checkIntervalMs = 1000, int idleThresholdSeconds = 5)
        {
            lastPosition = Cursor.Position;
            idleSeconds = idleThresholdSeconds;

            timer = new System.Windows.Forms.Timer();
            timer.Interval = checkIntervalMs;
            timer.Enabled = true;
            timer.Tick += Timer_Tick;
        }

        /// <summary>
        /// 开始监控鼠标
        /// </summary>
        public void Start()
        {
            lastPosition = Cursor.Position;
            timer.Tag = DateTime.Now;
            timer.Start();
        }

        /// <summary>
        /// 停止监控鼠标
        /// </summary>
        public void Stop()
        {
            timer.Stop();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            Point currentPosition = Cursor.Position;

            if (currentPosition == lastPosition)
            {
                if (timer.Tag == null)
                    timer.Tag = DateTime.Now;

                DateTime lastMoveTime = (DateTime)timer.Tag;
                if ((DateTime.Now - lastMoveTime).TotalSeconds >= idleSeconds)
                {
                    OnMouseIdle?.Invoke();
                    timer.Tag = DateTime.Now; // 重置计时，避免重复触发
                }
            }
            else
            {
                lastPosition = currentPosition;
                timer.Tag = DateTime.Now; // 更新移动时间
            }
        }
    }
}
